#include "notifyADT.h"
#include <sys/select.h>
       /* According to earlier standards */
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>


int
main(int argc, char* argv[])
{
    int i, result, len, ret;
    watchD w;
    fd_set rfds;
    char buf[BUF_LEN_NOTIF] = {0};
    struct inotify_event *event;
    char *test = NULL;


    /* zero-out the fd_set */
    FD_ZERO (&rfds);

    /*Inicializo w*/
    w.waList = NULL;
    if ((w.fd = notify()) == -1)
    {
        fprintf(stderr, "Error al al lamar a notify()\n");
        return 0;
    }

    FD_SET (w.fd, &rfds);

    if(setWatchs("./dir1", &w) == -1)
    {
        fprintf(stderr, "Error en setWatchs\n");
        return 0;
    }

    if(setWatchs("./dir2", &w) == -1)
    {
        fprintf(stderr, "Error en setWatchs\n");
        return 0;
    }


    ret = select (w.fd + 1, &rfds, NULL, NULL, NULL);

    if (ret < 0)
        perror ("select");
    else if (!ret)
        perror("select timeout");
    else if (FD_ISSET (w.fd, &rfds))
    {
//         while(1)
//         {
            len = read(w.fd, buf, BUF_LEN_NOTIF);
            if(len == -1)
            {
                fprintf(stderr, "Error en read\n");
                return 0;
            }
            i = 0;
            while (i < len)
            {
                event = (struct inotify_event *) &buf[i];

                printf ("wd=%d mask=%u cookie=%u len=%u\n",
                        event->wd, event->mask,
                        event->cookie, event->len);

                test = getWatchCompletePath(event, &w);
                printf("el archivo %s/%s fue modificado\n", test, event->name);
                free(test);

                if (event->len)
                        printf ("name=%s\n", event->name);

                if(update(&w, event) == -1)
                {
                    fprintf(stderr, "Error en upgrade\n");
                    return 0;
                }

                i += EVENT_SIZE + event->len;
            }
            freeWatch(&w);
//         }
    }

    return 0;
}

